use tauri::{command, AppHandle, Runtime, State, Window};

use model_graph_types::{
    database::{DataSource, DatabaseType},
    modeling::{system_meta_database, Value},
    transform::{
        DataTransformOptions, DataTransformUnit, DataTransformer, DomainTransformer,
        DomainTransformerOptions, DomainTransformerUnit,
    },
};

use data_transform::DefaultDataTransformer;

use super::ContextState;
use super::Result;

#[command]
pub async fn transform_data<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    source: DataSource,
    target: DataSource,
    units: Vec<DataTransformUnit>,
    options: DataTransformOptions,
) -> Result<bool> {
    let transform = DefaultDataTransformer {};
    let _ = transform.transform(&source, &target, units, options).await;

    Ok(true)
}

#[command]
pub async fn transform_domain<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    source: DataSource,
    target: DataSource,
    units: Vec<DomainTransformerUnit>,
    options: DomainTransformerOptions,
) -> Result<bool> {
    let transform = DefaultDataTransformer {};
    let _ = transform
        .transform_domain(&source, &target, units, options)
        .await;

    Ok(true)
}

#[command]
pub async fn transform_domain_export<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    source: DataSource,
    target: String,
    units: Vec<DomainTransformerUnit>,
    options: DomainTransformerOptions,
) -> Result<bool> {
    let transform = DefaultDataTransformer {};
    let _ = transform.write_file(&source, &target, units, options).await;

    Ok(true)
}

#[command]
pub async fn transform_domain_import<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    source: String,
    target: DataSource,
    units: Vec<DomainTransformerUnit>,
    options: DomainTransformerOptions,
) -> Result<bool> {
    let transform = DefaultDataTransformer {};
    let _ = transform.read_file(&source, &target, units, options).await;

    Ok(true)
}

#[command]
pub async fn transform_domain_clear<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    domains: Vec<String>,
) -> Result<bool> {
    let transform = DefaultDataTransformer {};
    let _ = transform
        .clear_domain(&system_meta_database()?, domains)
        .await;

    Ok(true)
}

#[command]
pub async fn transform_domain_delete<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    domains: Vec<String>,
) -> Result<bool> {
    let transform = DefaultDataTransformer {};
    let _ = transform
        .delete_domain(&system_meta_database()?, domains)
        .await;

    Ok(true)
}
